/*! @file main.cpp
    @version 1.6
    @brief Sample minimal test program for menusys
 */

#include <locale.h>
#include <stdio.h>
#include <menusys/menusys.h>
#include <menusys/menusysu.h>

// option (note: this is not thread-safe)
static int gOption = 0;

// handlers
extern void DoCommand(MSYS_Thread * thrd, MSYS_Args & aArgs);
extern void DoOption(MSYS_Thread * thrd, MSYS_Args & aArgs);

#ifdef _WIN32
extern const TCHAR  MSYS_DefaultOptionsFile[] = _T("menusys.cfg");
#else
extern const TCHAR  MSYS_DefaultOptionsFile[] = _T(".menusys");
#endif

int 
_tmain(
    int     argc, 
    TCHAR * argv[] )
{
    setlocale(LC_ALL, "");
    _ftprintf(stdout, 
        _T("MENUSYS TEST\n")
        _T("\n")
        _T("Note:\n")
        _T(" * help is available with '?' and '? /int'\n")
        _T(" * test command with:   'command'\n")
        _T(" * test option with:    'setopt'\n")
        _T(" * test variables with: 'setvar'\n")
        _T("\n")
        );
    const TCHAR * pInputFile = (argc > 1) ? argv[1] : NULL;
    return MSYS_Process(pInputFile, true) ? 0 : 1;
}

extern void 
MSYS_ThreadUserCreate(
    MSYS_Thread *       aNewThread,
    const MSYS_Thread * aParentThread
    )
{
    (void)aNewThread;
    (void)aParentThread;
}

extern void 
MSYS_ThreadUserDestroy(
    MSYS_Thread * aThread
    )
{
    (void)aThread;
}

extern void
MSYS_GetPrompt(
    MSYS_Thread *   aThread, 
    TCHAR *         aBuf,
    size_t          aBufSiz
    )
{
    (void) aThread;

    // prompt can be anything that you want
    _sntprintf(aBuf, aBufSiz, _T("%d> "), gOption);
}

const MSYS_DispatchEntry MSYS_Commands[] = {
    // options
    { _T("_setopt_option"), DoOption, false, _T("Test option."),
        _T("Test option extended help.")
    },

    // functions
    { MSYS_HEADER, NULL, false, _T("TEST FUNCTIONS"), NULL },
    { _T("command"), DoCommand, false, _T("Test command."),
        _T("Test command extended help.")
    },

    { NULL, NULL, false, NULL, NULL }
};

extern void DoCommand(MSYS_Thread * aThread, MSYS_Args & aArgs) 
{
    if (MSYS_NeedHelp(aThread, DoCommand, aArgs)) return;

    MSYS_Display(aThread, _T("Hello World!\n"));
    for (size_t n = 0; n < aArgs.size(); ++n) {
        MSYS_Display(aThread, _T("arg %d: %s\n"), n, aArgs[n]);
    }
}

extern void DoOption(MSYS_Thread * aThread, MSYS_Args & aArgs) 
{
    if (MSYS_NeedHelp(aThread, DoOption, aArgs)) return;

    const TCHAR * pAction = aArgs[0];
    const TCHAR * pOption = aArgs[1];
    const TCHAR * pValue  = aArgs.size() > 2 ? aArgs[2] : NULL;

    if (*pAction == _T('s')) { 
        gOption = _ttoi(pValue);
    }
    else { 
        TCHAR szBuf[20];
        _sntprintf(szBuf, 20, _T("%d"), gOption);
        MSYS_DisplayOption(aThread, pOption, szBuf);
    }
}
